<template>
  <div class="p-4">
    <div class="search_form">
      <Form ref="formRef" :model="searchForm" layout="inline">
        <FormItem label="所属公司" name="companyId" class="form_item_box">
          <Select
            allowClear
            v-model:value="searchForm.companyId"
            placeholder="请选择所属公司"
            style="width: 200px"
          >
            <SelectOption
              v-for="(item, index) in searchCompanyArr"
              :value="item.id"
              :key="index + 's'"
              >{{ item.name }}</SelectOption
            >
          </Select>
        </FormItem>
      </Form>
      <div class="search_btn"
        ><a-button type="primary" @click="getTableData">查询</a-button>
        <a-button @click="searchFormReset">重置</a-button>
      </div>
    </div>
    <div class="add_btn">
      <a-button type="primary" @click="showAddModal" v-if="isButtonVisible(16000001)"
        >添加合伙人</a-button
      >
    </div>
    <Table
      :dataSource="dataSource"
      :columns="columns"
      :pagination="pagination"
      @change="tableChangeFn"
    >
      <template #action="{ record }">
        <div class="table_action">
          <Popover trigger="click" placement="leftTop">
            <template #content>
              <div class="action_btn" @click="onEdit(record)" v-if="isButtonVisible(16000002)"
                >编辑</div
              >
              <div
                class="action_btn"
                @click="changePassAction(record)"
                v-if="isButtonVisible(16000004)"
                >修改密码</div
              >
              <Popconfirm
                :title="`您确定要删除${record.name}的账号吗？`"
                ok-text="确定"
                cancel-text="取消"
                @confirm="confirmDeletion(record)"
              >
                <div class="action_btn" v-if="isButtonVisible(16000003)">删除</div>
              </Popconfirm>
              <div
                class="action_btn"
                @click="menuPermissions(record)"
                v-if="isButtonVisible(16000005)"
                >修改权限</div
              ></template
            >
            <div class="action_btn">操作</div>
          </Popover>
        </div>
      </template>
    </Table>
    <BasicModal
      v-model:visible="addVisible"
      :title="
        isEdit == false ? (isChangePass == true ? '修改密码' : '添加合伙人账号') : '编辑合伙人账号'
      "
      @ok="onSubmit"
    >
      <Form
        class="form_box"
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 14 }"
      >
        <!-- <FormItem ref="id" label="职工编号" name="id">
          <Input v-model:value="formState.id" type="number" placeholder="请输入职工编号" />
        </FormItem> -->
        <div v-if="isChangePass == false">
          <FormItem label="所属公司" name="companyId">
            <Select
              allowClear
              v-model:value="formState.companyId"
              placeholder="请选择所属公司"
              :disabled="isEdit"
              @change="selectCompany"
            >
              <SelectOption v-for="(item, index) in companyArr" :value="item.id" :key="index">{{
                item.name
              }}</SelectOption>
            </Select>
            <div class="hint_txt">注：分公司添加账号选择公司无效,默认添加为当前公司</div>
          </FormItem>
          <FormItem ref="name" label="合伙人姓名" name="name">
            <Input v-model:value="formState.name" placeholder="请输入合伙人姓名" />
          </FormItem>
          <FormItem ref="account" label="账号" name="account">
            <Input
              v-model:value="formState.account"
              placeholder="请输入合伙人账号"
              :disabled="isEdit"
            />
          </FormItem>
          <FormItem ref="password" label="账号密码" name="password" v-if="isEdit == false">
            <Input
              v-model:value="formState.password"
              placeholder="请输入账号密码"
              type="password"
            />
          </FormItem>

          <FormItem ref="address" label="所在地址" name="address">
            <Input v-model:value="formState.address" placeholder="请输入所在地址" />
          </FormItem>
          <FormItem ref="contactPhone" label="联系电话" name="contactPhone">
            <Input v-model:value="formState.contactPhone" placeholder="请输入联系电话" />
          </FormItem>
        </div>
        <div v-if="isChangePass == true">
          <FormItem label="新密码" name="changePass">
            <Input
              v-model:value="formState.changePass"
              type="password"
              placeholder="请输入新密码"
            />
          </FormItem>
        </div>
      </Form>
    </BasicModal>
    <SelectTree ref="selectTree"></SelectTree>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted, reactive } from 'vue';
  import {
    Table,
    Modal,
    Form,
    Input,
    FormItem,
    Select,
    SelectOption,
    Textarea,
    Popconfirm,
    Checkbox,
    CheckboxGroup,
    Popover,
  } from 'ant-design-vue';
  import {
    companyAllSearch,
    addPartner,
    queryPartner,
    editPartner,
    changeEmployeePass,
    deletePartner,
    getCompanyRoutes,
  } from '/@/api/api';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicModal } from '/@/components/Modal';
  import SelectTree from '/@/views/dashboard/analysis/components/selectTree.vue';
  import { useRoute } from 'vue-router';
  let route = useRoute();
  const isButtonVisible = (id) => {
    let rulesArr = route?.meta?.rules?.map((rule) => rule.id) || [];
    return rulesArr.includes(id);
  };

  const { createMessage } = useMessage();

  const dataSource = ref([]);

  const columns = ref([
    {
      title: '编号',
      dataIndex: 'id',
      align: 'left',
      key: 'id',
      fixed: 'left',
    },
    {
      title: '公司名称',
      dataIndex: 'companyName',
      align: 'left',
      key: 'companyName',
    },
    {
      title: '合伙人',
      dataIndex: 'name',
      align: 'left',
      key: 'name',
    },
    {
      title: '账号',
      dataIndex: 'account',
      align: 'left',
      key: 'account',
    },
    {
      title: '联系电话',
      dataIndex: 'contactPhone',
      align: 'left',
      key: 'account',
    },
    {
      title: '合伙人所在地',
      dataIndex: 'address',
      align: 'left',
    },
    {
      title: '添加时间',
      dataIndex: 'createTime',
      align: 'left',
      key: 'createTime',
    },
    {
      title: '操作',
      dataIndex: 'action',
      align: 'left',
      slots: { customRender: 'action' },
      fixed: 'right',
      width: 100,
    },
  ]);
  const formRef = ref();
  const formState: any = reactive({
    companyId: '', //公司编号
    name: '',
    account: '',
    password: '',
    changePass: '',
    address: '', //所在地址
    contactPhone: '', //联系电话
  });
  const rules = {
    // id: [{ required: true, message: '请输入公司编号', trigger: 'blur' }],
    name: [{ required: true, message: '请输入合伙人姓名', trigger: 'blur' }],
    account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
    companyId: [{ required: true, message: '请选择公司' }],
    password: [{ required: true, message: '请输入账号密码' }],
    address: [{ required: true, message: '请输入所在地址' }],
    contactPhone: [{ required: true, message: '请输入联系电话' }],
    changePass: [{ required: true, message: '请输入新的账号密码' }],
  };
  const isEdit = ref(false);
  const editData = ref({});
  const onEdit = (e) => {
    isEdit.value = true;
    addVisible.value = true;
    isChangePass.value = false;
    editData.value = e;
    formState.companyId = e.companyId;
    formState.name = e.name;
    formState.account = e.account;
    formState.address = e.address;
    formState.contactPhone = e.contactPhone;
  };
  // 选择所属公司变化事件，改变是请求公司菜单
  const routersAll = ref([]);
  const selectCompany = (e) => {
    console.log(e);
    getCompanyRoutes({
      companyId: e,
    }).then((res) => {
      console.log(res);
      routersAll.value = res;
    });
  };
  // 设置权限
  const selectTree = ref(); //合同
  const menuPermissions = (record) => {
    console.log(record);
    // 总公司账号给职工设置权限时获取公司的权限分给账户
    selectTree.value.init({
      comid: record.companyId,
      peoId: record.id,
      kind: 'headOffice',
    });
  };

  const isChangePass = ref(false);
  const changePassAction = (e) => {
    isEdit.value = false;
    addVisible.value = true;
    isChangePass.value = true;
    editData.value = e;
  };
  // 确认删除
  const confirmDeletion = (e) => {
    deletePartner({
      ...e,
    }).then(() => {
      createMessage.success('删除成功');
      getTableData();
    });
  };

  const onSubmit = () => {
    formRef.value
      .validate()
      .then(() => {
        if (isEdit.value == true && isChangePass.value == false) {
          // 编辑模式
          const { password, ...restFormState } = formState;
          editPartner({
            ...restFormState,
            id: editData.value.id,
          }).then(() => {
            createMessage.success('编辑成功');
            resetForm();
            addVisible.value = false;
            getTableData();
          });
        } else if (isChangePass.value == true && isEdit.value == false) {
          // 修改密码模式 changeEmployeePass
          changeEmployeePass({
            password: formState.changePass,
            id: editData.value.id,
          }).then(() => {
            createMessage.success('修改成功');
            resetForm();
            addVisible.value = false;
            // getTableData();
          });
        } else {
          addPartner({
            ...formState,
          }).then(() => {
            createMessage.success('添加成功');
            resetForm();
            addVisible.value = false;
            getTableData();
          });
        }
      })
      .catch((error: any) => {
        console.log('error', error);
      });
  };
  const resetForm = () => {
    for (let key in formState) {
      formState[key] = '';
    }
  };
  // 弹窗相关
  const addVisible = ref<boolean>(false);
  const showAddModal = () => {
    resetForm();
    isEdit.value = false;
    isChangePass.value = false;
    addVisible.value = true;
  };

  const getTableData = async () => {
    try {
      const response = await queryPartner({
        page: pagination.value.current,
        limit: pagination.value.pageSize,
        companyId: searchForm.companyId,
      });
      pagination.value.total = response.total;
      dataSource.value = response.items;
      console.log(response);
    } catch (error) {
      console.error('An error occurred while fetching data:', error);
    }
  };
  const companyArr = ref([]);
  const searchCompanyArr = ref([]);
  onMounted(() => {
    getTableData();
    companyAllSearch().then((res) => {
      // companyArr.value = res;
      companyArr.value = res.filter((item) => item.id !== 10000000);
      searchCompanyArr.value = res;
    });
  });
  //分页器对象
  const pagination = ref({
    current: '1',
    pageSize: '10',
    pageSizeOptions: ['10', '20', '50', '100'],
    total: 0,
    showTotal: (totals) => `总${totals}条数据`,
    showSizeChanger: true,
  });

  // table变化时出发  筛选/跳转
  const tableChangeFn = (e) => {
    pagination.value.current = String(e.current);
    pagination.value.pageSize = String(e.pageSize);
    console.log(e, 'e');
    getTableData();
  };

  // 搜索表单参数
  const searchForm = reactive({
    companyId: undefined,
  });
  // 搜索表单参数重置
  const searchFormReset = () => {
    searchForm.companyId = undefined;
    getTableData();
  };
</script>

<style lang="less" scoped>
  .add_btn {
    margin: 0 0 15px 0;
  }
  .form_box {
    padding: 20px;
  }
  .table_action {
    color: rgb(25, 144, 255);
  }
  .action_btn {
    color: #1990ff;
    cursor: pointer;
    margin: 5px 0;
  }
  .hint_txt {
    font-size: 10px;
    color: red;
  }

  .search_form {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    min-height: 90px;
    .search_btn {
      width: 10%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      > button {
        margin: 5px 0;
      }
    }
  }

  ::v-deep .form_item_box {
    .ant-form-item-label {
      width: auto;
    }
  }
</style>
